package com.imay.live.manager;

import android.content.Context;

import com.danikula.videocache.*;

import java.io.File;

/**
 * Created by Administrator on 2017/6/21 0021.
 */

public class VideoManager implements com.danikula.videocache.CacheListener {

    public static String TAG = "VideoManager";

    private static VideoManager videoManager;

    private HttpProxyCacheServer proxy; //视频代理

    public File cacheFile;

    private int buffterPoint;

    public static synchronized VideoManager instance() {
        if (videoManager == null) {
            videoManager = new VideoManager();
        }
        return videoManager;
    }

    /**
     * 获取缓存代理服务
     */
    public static HttpProxyCacheServer getProxy(Context context) {
        HttpProxyCacheServer proxy = VideoManager.instance().proxy;
        return proxy == null ? (VideoManager.instance().proxy =
                VideoManager.instance().newProxy(context)) : proxy;
    }

    /**
     * 获取缓存代理服务,带文件目录的
     */
    public static HttpProxyCacheServer getProxy(Context context, File file) {

        //如果为空，返回默认的
        if (file == null) {
            return getProxy(context);
        }

        //如果已经有缓存文件路径，那么判断缓存文件路径是否一致
        if (VideoManager.instance().cacheFile != null
                && !VideoManager.instance().cacheFile.getAbsolutePath().equals(file.getAbsolutePath())) {
            //不一致先关了旧的
            HttpProxyCacheServer proxy = VideoManager.instance().proxy;

            if (proxy != null) {
                proxy.shutdown();
            }
            //开启新的
            return (VideoManager.instance().proxy =
                    VideoManager.instance().newProxy(context, file));
        } else {
            //还没有缓存文件的或者一致的，返回原来
            HttpProxyCacheServer proxy = VideoManager.instance().proxy;

            return proxy == null ? (VideoManager.instance().proxy =
                    VideoManager.instance().newProxy(context, file)) : proxy;
        }
    }

    /**
     * 创建缓存代理服务,带文件目录的.
     */
    private HttpProxyCacheServer newProxy(Context context, File file) {
        if (!file.exists()) {
            file.mkdirs();
        }
        HttpProxyCacheServer.Builder builder = new HttpProxyCacheServer.Builder(context);
        builder.cacheDirectory(file);
        cacheFile = file;
        return builder.build();
    }

    /**
     * 创建缓存代理服务
     */
    private HttpProxyCacheServer newProxy(Context context) {
        return new HttpProxyCacheServer(context.getApplicationContext());
    }

    public VideoManager() {
    }

    public void releaseMediaPlayer() {
        if (proxy != null) {
            proxy.unregisterCacheListener(VideoManager.this);
        }
        buffterPoint = 0;
    }


    @Override
    public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
        buffterPoint = percentsAvailable;
    }
}
